import * as THREE from 'three';
import { useEffect } from 'react';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

/**
 * 展示车道中心线
 */
// shape转数组
export function parseShape(shape) {
  return shape.split(' ').map(coord => coord.split(',').map(Number));
}

function APP() {
  useEffect(() => { 
    /** 创建场景 */
    const scene = new THREE.Scene(); // 创建场景

    /** 创建相机 */
    const width = window.innerWidth; // 窗口宽度
    const height = window.innerHeight; // 窗口高度
    const k = width / height; // 窗口长宽比
    const s = 200; // 三维场景显示范围控制系数，系数越大，显示的范围越大
    const camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    camera.position.set(0, 0, 500); // 设置相机位置
    camera.lookAt(scene.position); // 设置相机指示方向（指向场景）

    /** 创建渲染器对象 */
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height); //设置渲染区域尺寸
    // renderer.setClearColor(0x888888, 1); //设置背景颜色
    document.body.appendChild(renderer.domElement); //body元素中插入canvas对象
    
    function render() { 
      renderer.render(scene, camera); //执行渲染操作
    }

    const controls = new OrbitControls(camera, renderer.domElement)
    controls.addEventListener("change", () => {
      render()
    }); //监听鼠标、键盘事件

    const edge = {
      id: ":10_2",
      lane: [
        {
          id: ":10_2_0",
          index: "0",
          speed: "6.49",
          length: "9.03",
          shape: "-10,0 10,0" // 车道的中心线
        },
      ]
    }
    const cords = edge.lane.map(lane => {
      return parseShape(lane.shape).map(coord=> new THREE.Vector3(coord[0],coord[1]))
    })
    
    for (let i = 0; i < cords.length; i++) {
      const cord = cords[i];
      const curve = new THREE.LineCurve3(cord[0],cord[1])
      const points = curve.getPoints()
      // 创建一个顶点缓冲几何体
      const geometry = new THREE.BufferGeometry().setFromPoints( points );
      // 线条渲染模式
      const material = new THREE.LineBasicMaterial({
        color: 0xffffff, //线条颜色
      });
      // 创建线模型对象   构造函数：Line、LineLoop、LineSegments
      const line = new THREE.Line( geometry, material );
      // 把物体添加进场景中
      scene.add( line );
    }
    render();
  }, [])
  return (
    <div className='APP'></div>
  )
}

export default APP;